package com.yanqu.road.dao.impl.player;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.ChannelUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ChannelUserBaseInfoDaoImpl extends TempDataObjectDao<ChannelUserBaseInfo> {
    public static String getUserBaseInfoSql = "select * from t_n_user_base_info ";

    public Map<Long, ChannelUserBaseInfo> getAllUserBaseInfo() {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, ChannelUserBaseInfo> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getChannelServerDb());
            call = getDb().getConnection().prepareCall(getUserBaseInfoSql);
            int i = 1;
            rs = call.executeQuery();
            while (rs.next()) {
                ChannelUserBaseInfo data = parse(rs);
                if (data == null || data.getUserBaseInfo() == null) {
                    continue;
                }
                dataMap.put(data.getUserId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }


    @Override
    protected boolean updateData(ChannelUserBaseInfo data) {
        String sql = "REPLACE INTO t_n_user_base_info(userId,userBaseInfo,lastUpdateTime) VALUES(?,?,?)";
        try {
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            getDb().setConnName(DbNameStrategy.getChannelServerDb());
            int i = 1;
            Map<Integer, DbParameter> para = new HashMap<>();
            para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
            para.put(i++, new DbParameter(Types.NVARCHAR, JSON.toJSONString(data.getUserBaseInfo())));
            para.put(i++, new DbParameter(Types.BIGINT, data.getLastUpdateTime()));
            mapList.add(para);
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    public static String insertStrongholdWildBoxSql = "REPLACE into t_n_user_base_info(userId,userBaseInfo,lastUpdateTime) values (?,?,?)";

    @Override
    protected boolean addData(ChannelUserBaseInfo data) {
        data.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getChannelServerDb());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.BIGINT, data.getUserId()));
        para.put(i++, new DbParameter(Types.NVARCHAR, JSON.toJSONString(data.getUserBaseInfo())));
        para.put(i++, new DbParameter(Types.BIGINT, data.getLastUpdateTime()));
        if (getDb().executeNoneQuery(insertStrongholdWildBoxSql, para) > 0) {
            return true;
        }
        return false;

    }

    @Override
    protected ChannelUserBaseInfo parseData(ResultSet rs) throws SQLException {
        ChannelUserBaseInfo data = new ChannelUserBaseInfo();
        data.setUserId(rs.getLong("userId"));
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        data.setUserBaseInfo(JSON.parseObject(rs.getString("userBaseInfo"), new TypeReference<UserBaseInfo>() {
        }));
        return data;
    }

    public static String getUserBaseInfoInTimeSql = "select * from t_n_user_base_info where lastUpdateTime >= ?";
    public Map<Long, ChannelUserBaseInfo> getUserBaseInfoUpdateInTime(long startTime) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Long, ChannelUserBaseInfo> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getChannelServerDb());
            call = getDb().getConnection().prepareCall(getUserBaseInfoInTimeSql);
            int i = 1;
            call.setLong(i++, startTime);
            rs = call.executeQuery();
            while (rs.next()) {
                ChannelUserBaseInfo data = parse(rs);
                if (data == null || data.getUserBaseInfo() == null) {
                    continue;
                }
                dataMap.put(data.getUserId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }
    public static String getUserBaseInfoByUserIdSql = "select * from t_n_user_base_info where userId = ?";
    public ChannelUserBaseInfo getUserBaseInfoByUserId(long userId) {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getChannelServerDb());
            call = getDb().getConnection().prepareCall(getUserBaseInfoByUserIdSql);
            int i = 1;
            call.setLong(i++, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }
}
